package com.gjs.common.manager;

import lombok.Getter;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SwaggerConfigurator {

    /**
     * 默认全局响应列表
     */
    public static final List<ResponseMessage> DEFAULT_GLOBAL_RESPONSE_LIST = Stream.of(new ResponseMessageBuilder().code(500).message("请求失败").build()).collect(Collectors.toList());

    /**
     * Docket对象
     */
    @Getter
    private Docket docket;

    public SwaggerConfigurator() {
        this.docket = new Docket(DocumentationType.SWAGGER_2);
    }

    /**
     * 配置全局响应
     *
     * @param responseMessages List<ResponseMessage>
     * @return SwaggerConfigurator
     */
    public SwaggerConfigurator globalResponse(List<ResponseMessage> responseMessages) {
        this.docket.globalResponseMessage(RequestMethod.GET, responseMessages);
        this.docket.globalResponseMessage(RequestMethod.POST, responseMessages);
        return this;
    }

    /**
     * 配置API文档信息
     *
     * @param apiDocName String 文档名称
     * @return SwaggerConfigurator
     */
    public SwaggerConfigurator apiInfo(String apiDocName) {
        this.docket.apiInfo(new ApiInfoBuilder().title(apiDocName).build());
        return this;
    }

    /**
     * 配置API文档信息
     *
     * @param apiInfo ApiInfo
     * @return SwaggerConfigurator
     */
    public SwaggerConfigurator apiInfo(ApiInfo apiInfo) {
        this.docket.apiInfo(apiInfo);
        return this;
    }

    /**
     * 配置API需要后台鉴权
     *
     * @return SwaggerConfigurator
     */
    public SwaggerConfigurator backendAuth() {
        AuthorizationScope[] authorizationScopes = {new AuthorizationScope("global", "accessEverything")};

        List<SecurityReference> defaultAuth = Stream
                .of(
                        SecurityReference.builder().reference("token").scopes(authorizationScopes).build(),
                        SecurityReference.builder().reference("access_token").scopes(authorizationScopes).build()
                )
                .collect(Collectors.toList());

        List<SecurityContext> securityContexts = Stream
                .of(new SecurityContext(defaultAuth, PathSelectors.any()))
                .collect(Collectors.toList());

        this.docket
                .securitySchemes(Stream.of(new ApiKey("token", "token", "header"),new ApiKey("access_token", "access_token", "query")).collect(Collectors.toList()))
                .securityContexts(securityContexts);

        return this;
    }
}
